<?php
/**
 * JamNews Install
 *
 * Plugin install script which adds custom post type, taxonomies, and database tables to WordPress. Runs on activation and upgrade.
 *
 * @author 		VoAnhKiet
 * @category 	Admin
 * @package 	JamNews/Admin/Install
 * @version     1.0.0
 */

if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

/**
 * Runs the installer.
 *
 * @access public
 * @return void
 */
function do_install_jamnews(){
	global $jamnews;
	
	jamnews_tables_install();
	
	// Queue upgrades
	$current_version = get_option( 'jamnews_version', null );
	$current_db_version = get_option( 'jamnews_db_version', null );

	if ( version_compare( $current_db_version, '3.5.0', '<' ) && null !== $current_db_version ) {
		update_option( '_jamnews_needs_update', 1 );
	} else {
		update_option( 'jamnews_db_version', $jamnews->version );
	}
	// Update version
	update_option( 'jamnews_version', $jamnews->version );
	
	// add capability manager_jamnews
	$role = get_role( 'administrator' );
	$role->add_cap("manager_jamnews");
}

/**
 * Set up the database tables which the plugin needs to function.
 */
function jamnews_tables_install(){
	global $wpdb, $jamnews;
	
	$wpdb->hide_errors();

	$collate = '';

    if ( $wpdb->has_cap( 'collation' ) ) {
		if( ! empty($wpdb->charset ) )
			$collate .= "DEFAULT CHARACTER SET $wpdb->charset";
		if( ! empty($wpdb->collate ) )
			$collate .= " COLLATE $wpdb->collate";
    }
	
	require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
	
	// Jamnew Tables
	$jamnews_tables = "
	CREATE TABLE {$jamnews->table_name} (
		  id int(11) NOT NULL auto_increment,
		  parent_id int(11) NULL,
		  meta_key varchar(200) NULL,
		  meta_value longtext NULL,
		  namespace varchar(55) NOT NULL DEFAULT 'post_type',
		  status int(2) NOT NULL DEFAULT 1,
		  menu_order int(11) NOT NULL DEFAULT 0,
		  PRIMARY KEY  (id)
	) $collate;";
	dbDelta($jamnews_tables);
} 


?>